using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Tools;

namespace ToolWindows
{
    public partial class Queues : UserControl
    {
        private string current_database = string.Empty;
        private string connectionString = null;

        public string CurrentDatabase
        {
            set
            {
                current_database = value;
            }
        }

        public Queues()
        {
            InitializeComponent();
        }

        public void RefreshData()
        {
            connectionString = UtilitySqlTools.Current.ConnectionString();

            if (connectionString == null)
            {
                return;
            }

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    StringBuilder sb = new StringBuilder();

                    sb.AppendLine("USE [" + current_database + "];");
                    sb.AppendLine("SELECT   s.name [Queue name],");
                    sb.AppendLine("         s.object_id, ");
                    sb.AppendLine("         dp.name [Principal], ");
                    sb.AppendLine("         sch.name [Schema], ");
                    sb.AppendLine("         case s.is_ms_shipped when 1 then 'Yes' else null end [Is MS shipped?], ");
                    sb.AppendLine("         case s.is_published when 1 then 'Yes' else null end [Is published?], ");
                    sb.AppendLine("         s.max_readers [Max readers], ");
                    sb.AppendLine("         s.activation_procedure [Activation procedure], ");
                    sb.AppendLine("         dpe.name [Execute as principal], ");
                    sb.AppendLine("         case s.is_activation_enabled when 1 then 'Yes' else null end [Is activation enabled?], ");
                    sb.AppendLine("         case s.is_receive_enabled when 1 then 'Yes' else null end [Is receive enabled?], ");
                    sb.AppendLine("         case s.is_enqueue_enabled when 1 then 'Yes' else null end [Is enqueue enabeld?], ");
                    sb.AppendLine("         case s.is_retention_enabled when 1 then 'Yes' else null end [Is retention enabled] ");
                    sb.AppendLine("FROM sys.service_queues s ");
                    sb.AppendLine("LEFT JOIN sys.database_principals dp on s.principal_id = dp.principal_id");
                    sb.AppendLine("LEFT JOIN sys.database_principals dpe on s.execute_as_principal_id = dpe.principal_id");
                    sb.AppendLine("INNER JOIN sys.schemas sch on s.schema_id = sch.schema_id ");
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = new SqlCommand();
                    da.SelectCommand.CommandText = sb.ToString();
                    da.SelectCommand.CommandTimeout = 0;
                    da.SelectCommand.CommandType = CommandType.Text;
                    da.SelectCommand.Connection = connection;

                    DataSet ds = new DataSet();
                    da.Fill(ds);

                    dgvQueues.DataSource = ds.Tables[0];
                    dgvQueues.Columns["object_id"].Visible = false;

                    connection.Close();
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void dgvServiceQueues_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            connectionString = UtilitySqlTools.Current.ConnectionString();

            if (connectionString == null)
            {
                return;
            }

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    string queue_name = dgvQueues.Rows[e.RowIndex].Cells["Queue name"].Value.ToString();
                    string schema = dgvQueues.Rows[e.RowIndex].Cells["Schema"].Value.ToString();

                    StringBuilder sb = new StringBuilder();

                    sb.AppendLine("USE [" + this.current_database + "];");
                    sb.AppendLine("SELECT   case Status when 0 then 'Ready' when 1 then 'Received' when 2 then 'Not yet complete' when 3 then 'Retained sent message' else '???' end [Status],");
                    sb.AppendLine("         Priority, ");
                    sb.AppendLine("         queuing_order [Queuing order], ");
                    sb.AppendLine("         upper(conversation_group_id) [Conversation group ID], ");
                    sb.AppendLine("         message_sequence_number [Message sequence number], ");
                    sb.AppendLine("         service_name [Service name], ");
                    sb.AppendLine("         service_contract_name [Service contract name], ");
                    sb.AppendLine("         message_type_name [Message type name], ");
                    sb.AppendLine("         validation [Validation], ");
                    sb.AppendLine("         case when validation = 'X' then cast(message_body as xml) else cast(message_body as nvarchar(max)) end [Message body] ");
                    sb.AppendLine("FROM [" + schema + "].[" + queue_name + "]");
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = new SqlCommand();
                    da.SelectCommand.CommandText = sb.ToString();
                    da.SelectCommand.CommandTimeout = 0;
                    da.SelectCommand.CommandType = CommandType.Text;
                    da.SelectCommand.Connection = connection;

                    DataSet ds = new DataSet();
                    da.Fill(ds);

                    dgvQueuesContent.DataSource = ds.Tables[0];

                    connection.Close();
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }


    }
}
